<template>
  <my-map height="100%">
    <my-map-placement placement="left-top" style="padding: 10px;">
      <el-button size="small" :disabled="mode==='draw'" @click="draw">绘画模式</el-button>
      <el-button size="small" :disabled="mode==='modify'" @click="modify">编辑模式</el-button>
      <el-button size="small" :disabled="mode==='finish'" @click="finish">结束</el-button>
      <el-button size="small" @click="getFeatures">获取图形</el-button>
      <el-button size="small" type="primary" @click="save">保存</el-button>
      <el-button size="small" @click="clear">清空</el-button>
    </my-map-placement>
    <my-map-draw ref="draw" @ready="handleReady" manual></my-map-draw>
  </my-map>
</template>

<script>
  import {save, get, LOCAL} from '$ui/utils/storage'

  const cacheKey = '__draw_feature__'
  export default {
    data() {
      return {
        mode: 'finish'
      }
    },
    methods: {
      handleReady() {
        const json = get(cacheKey, LOCAL)
        if (json) {
          this.$refs.draw.fromJSON(json)
        }
      },
      draw() {
        this.$refs.draw.finish()
        this.$refs.draw.draw()
        this.mode = 'draw'
      },
      modify() {
        this.$refs.draw.finish()
        this.$refs.draw.modify()
        this.mode = 'modify'
      },
      finish() {
        this.$refs.draw.finish()
        this.mode = 'finish'
      },
      getFeatures() {
        const features = this.$refs.draw.getFeatures()
        alert('当前有' + features.length + '个图形')
      },
      clear() {
        this.$refs.draw.clear()
        this.save()
      },
      save() {
        this.$nextTick(() => {
          const json = this.$refs.draw.toJSON()
          save(cacheKey, json, LOCAL)
        })
      }
    }
  }
</script>
